import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Card,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Button,
  IconButton,
  Chip,
  Typography,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  FormControlLabel,
  Radio,
  RadioGroup,
  Alert,
  Snackbar,
} from '@mui/material';
import { Iconify } from 'src/components/iconify';
import { DashboardContent } from 'src/layouts/dashboard';
import { getDictTypeList, saveDictType, updateDictType, deleteDictType, DictType } from 'src/api/dict-api';

export function DictTypeView() {
  const navigate = useNavigate();
  const [dictTypes, setDictTypes] = useState<DictType[]>([]);
  const [loading, setLoading] = useState(false);
  const [openDialog, setOpenDialog] = useState(false);
  const [editingType, setEditingType] = useState<DictType | null>(null);
  const [snackbar, setSnackbar] = useState({ open: false, message: '', severity: 'success' as 'success' | 'error' });

  // 表单状态
  const [formData, setFormData] = useState<DictType>({
    name: '',
    code: '',
    description: '',
    enabled: 0, // 0表示启用，1表示不启用
    sort: 0,
    icon: '',
    color: '#1976d2',
  });

  // 加载字典类型列表
  const loadDictTypes = async () => {
    setLoading(true);
    try {
      const response = await getDictTypeList();
      if (response.success) {
        setDictTypes(response.data);
      } else {
        showSnackbar('加载字典类型失败', 'error');
      }
    } catch (error) {
      showSnackbar('加载字典类型失败', 'error');
    } finally {
      setLoading(false);
    }
  };

  // 显示消息提示
  const showSnackbar = (message: string, severity: 'success' | 'error') => {
    setSnackbar({ open: true, message, severity });
  };

  // 打开新增对话框
  const handleAdd = () => {
    setEditingType(null);
    setFormData({
      name: '',
      code: '',
      description: '',
      enabled: 0, // 0表示启用，1表示不启用
      sort: 0,
      icon: '',
      color: '#1976d2',
    });
    setOpenDialog(true);
  };

  // 打开编辑对话框
  const handleEdit = (type: DictType) => {
    setEditingType(type);
    setFormData({
      name: type.name,
      code: type.code,
      description: type.description || '',
      enabled: type.enabled === 0 ? 0 : 1, // 0表示启用，1表示不启用
      sort: type.sort || 0,
      icon: type.icon || '',
      color: type.color || '#1976d2',
    });
    setOpenDialog(true);
  };

  // 删除字典类型
  const handleDelete = async (id: string) => {
    if (!id) return;
    
    try {
      const response = await deleteDictType(id);
      if (response.success) {
        showSnackbar('删除成功', 'success');
        loadDictTypes();
      } else {
        showSnackbar('删除失败', 'error');
      }
    } catch (error) {
      showSnackbar('删除失败', 'error');
    }
  };

  // 查看字典数据
  const handleViewData = (type: DictType) => {
    navigate(`/dict-data?typeId=${type.id}&typeName=${encodeURIComponent(type.name)}`);
  };

  // 保存字典类型
  const handleSave = async () => {
    try {
      const response = editingType
        ? await updateDictType({ ...formData, id: editingType.id })
        : await saveDictType(formData);
      
      if (response.success) {
        showSnackbar(editingType ? '更新成功' : '保存成功', 'success');
        setOpenDialog(false);
        loadDictTypes();
      } else {
        showSnackbar(editingType ? '更新失败' : '保存失败', 'error');
      }
    } catch (error) {
      showSnackbar(editingType ? '更新失败' : '保存失败', 'error');
    }
  };

  // 初始化加载
  useEffect(() => {
    loadDictTypes();
  }, []);

  return (
    <DashboardContent>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h5">字典类型管理</Typography>
        <Button
          variant="contained"
          startIcon={<Iconify icon="eva:plus-fill" />}
          onClick={handleAdd}
        >
          新增字典类型
        </Button>
      </Box>

      <Card>
        <TableContainer component={Paper}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>名称</TableCell>
                <TableCell>编码</TableCell>
                <TableCell>描述</TableCell>
                <TableCell>状态</TableCell>
                <TableCell>排序</TableCell>
                <TableCell>图标</TableCell>
                <TableCell>颜色</TableCell>
                <TableCell>创建时间</TableCell>
                <TableCell>操作</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {dictTypes.map((type) => (
                <TableRow key={type.id}>
                  <TableCell>{type.name}</TableCell>
                  <TableCell>{type.code}</TableCell>
                  <TableCell>{type.description}</TableCell>
                  <TableCell>
                    <Chip
                      label={type.enabled === 0 ? '启用' : '禁用'}
                      color={type.enabled === 0 ? 'success' : 'default'}
                      size="small"
                    />
                  </TableCell>
                  <TableCell>{type.sort}</TableCell>
                  <TableCell>{type.icon}</TableCell>
                  <TableCell>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <Box
                        sx={{
                          width: 20,
                          height: 20,
                          borderRadius: '50%',
                          backgroundColor: type.color,
                        }}
                      />
                      {type.color}
                    </Box>
                  </TableCell>
                  <TableCell>{type.createDate}</TableCell>
                                     <TableCell>
                     <IconButton onClick={() => handleViewData(type)} color="info" title="查看数据">
                       <Iconify icon="eva:list-fill" />
                     </IconButton>
                     <IconButton onClick={() => handleEdit(type)} color="primary" title="编辑">
                       <Iconify icon="eva:edit-fill" />
                     </IconButton>
                     <IconButton onClick={() => handleDelete(type.id!)} color="error" title="删除">
                       <Iconify icon="eva:trash-2-fill" />
                     </IconButton>
                   </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      </Card>

      {/* 新增/编辑对话框 */}
      <Dialog open={openDialog} onClose={() => setOpenDialog(false)} maxWidth="md" fullWidth>
        <DialogTitle>{editingType ? '编辑字典类型' : '新增字典类型'}</DialogTitle>
        <DialogContent>
          <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 2, mt: 2 }}>
            <TextField
              label="名称"
              value={formData.name}
              onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              fullWidth
              required
            />
            <TextField
              label="编码"
              value={formData.code}
              onChange={(e) => setFormData({ ...formData, code: e.target.value })}
              fullWidth
              required
            />
            <TextField
              label="描述"
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              fullWidth
              multiline
              rows={2}
            />
            <TextField
              label="排序"
              type="number"
              value={formData.sort}
              onChange={(e) => setFormData({ ...formData, sort: parseInt(e.target.value) || 0 })}
              fullWidth
            />
            <TextField
              label="图标"
              value={formData.icon}
              onChange={(e) => setFormData({ ...formData, icon: e.target.value })}
              fullWidth
            />
            <TextField
              label="颜色"
              value={formData.color}
              onChange={(e) => setFormData({ ...formData, color: e.target.value })}
              fullWidth
            />
                         <RadioGroup
               value={formData.enabled}
               onChange={(e) => setFormData({ ...formData, enabled: parseInt(e.target.value) })}
               row
             >
               <FormControlLabel value={0} control={<Radio />} label="启用" />
               <FormControlLabel value={1} control={<Radio />} label="禁用" />
             </RadioGroup>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenDialog(false)}>取消</Button>
          <Button onClick={handleSave} variant="contained">
            {editingType ? '更新' : '保存'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* 消息提示 */}
      <Snackbar
        open={snackbar.open}
        autoHideDuration={6000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
      >
        <Alert severity={snackbar.severity} onClose={() => setSnackbar({ ...snackbar, open: false })}>
          {snackbar.message}
                          </Alert>
        </Snackbar>
     </DashboardContent>
   );
 }
